# -*- coding: utf8 -*-

import sqlanydb,settings
from mylog import MyLog


class IQConnection:
    def __init__(self, dbargs):
        self.connect = sqlanydb.connect(userid=dbargs['userid'], password=dbargs['password'], host=dbargs['host'])

    def __del__(self):
        self.connect.close()


    def object_exists(self,object_name):
        ret = False
        _sql = """select 1 from sysobjects where name = '{obj}'"""
        _sql = _sql.format(obj=object_name)
        cur = self.connect.cursor()
        cur.execute(_sql)
        s = cur.fetchall()
        for i in s:
            if i[0]==1:
                ret = True
        cur.close()
        return ret


    def create_table(self,table):
        _sql = """create table {tablename}("""+settings.TARGET_TABLE_STRUCTURE+""")"""
        _sql = _sql.format(tablename=table)
        MyLog.info(_sql)
        cur = self.connect.cursor()
        try:
            cur.execute(_sql)
        except Exception,e:
            MyLog.info('create  table faild:%s' % e)
        cur.close()


    def load_table(self,srcfile,table,sep,end_symbol='0x0a',columns_set=tuple()):
        _load_sql = """load table %s (%s) from '%s' escapes off quotes off with checkpoint on """
        column_str = (" '"+sep+"',").join(columns_set)+' '+end_symbol
        _sql = _load_sql % (table, column_str, srcfile)
        MyLog.info(_sql)
        cur = self.connect.cursor()
        cur.execute(_sql)
        cur.close()
        self.connect.commit()

